package com.example.day04.exercise;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

/**
 * 重写ArrayList   、、、
 *  泛型      T  E  K V ? ..........
 * @param <E>
 */
public class MyArrayList<E> {
        //jdk 5.x  开始提供泛型，保证集合是类型安全的集合

     private  int size;

     private  Object[] data;

    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};

    public  MyArrayList(){
        //数组初始化
            data=EMPTY_ELEMENTDATA;
    }

     public  void add(E e){
         ensureCapacityInternal(size+1);
         data[size++]=e;
     }

    private void ensureCapacityInternal(int minCapacity) {
        //判断是否是第一次添加
        if(this.data==EMPTY_ELEMENTDATA){
            minCapacity=Math.max(minCapacity,DEFAULT_CAPACITY);
        }
        if(minCapacity> data.length){
            int oldcapatity= data.length;
            int newcapatity=oldcapatity+(oldcapatity>>1);
            if(newcapatity-minCapacity<0){
                newcapatity=minCapacity;
            }
            //数组扩容
            data= Arrays.copyOf(data,newcapatity);
        }
    }

    //根据索引下标删除元素
    public  void  remove(int index){
        // 1 2 3 4 5 6  index=3
        // 1 2 3 5 6 6    size=6
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(data, index+1, data, index,
                    numMoved);
        // size=6   ->5 data[5]=null   data.length =5   1  2 3  5  6
        data[--size] = null; // clear to let GC do its work


     }

     //删除第一个和传入元素相同的元素 其他不删除
     public  void remove(E e){
            int count=0;
            /// 1  2 3 4 4 4 5 6
            Object[] temp=new Object[size-1];
            for(int i=0;i<size;i++){
                if(data[i]!=e){
                    count++;
                }else{
                    break;
                }
            }
            System.arraycopy(data,0,temp,0,count);
            System.arraycopy(data,count+1,temp,count,size-count-1);
            //原来数组长度减一
            data[--size]=null;
            //将新的数组赋值给原来的数组
            data=temp;


     }

    @Override
    public String toString() {
            return  Arrays.toString(Arrays.copyOf(data,size));
    }
}

class  TestArraylist{
    public static void main(String[] args) {
        MyArrayList<Integer> lists=new MyArrayList<>();
        lists.add(1);
        lists.add(2);
        lists.add(3);
        lists.add(4);
        lists.add(4);
        lists.add(4);
        lists.add(5);
        lists.add(6);
        Integer  k=4;
        System.out.println(lists);

        lists.remove(1);

        System.out.println(lists);

        StringBuffer sb=new StringBuffer();
        sb.append("[");
        sb.append("a");
        sb.append("b");
        sb.append("c");
        sb.append("d");
        sb.append("]");

        System.out.println(sb);


    }
}
